package top.zlcode.friend.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zlcode.common.core.constants.CacheConstants;
import top.zlcode.common.redis.service.RedisService;
import top.zlcode.friend.domain.question.UserFavoriteQuestion;
import top.zlcode.friend.mapper.question.UserFavoriteQuestionMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户收藏题目缓存管理器
 *
 * @author zlcode
 */
@Component
public class UserFavoriteQuestionCacheManager {

    @Autowired
    private RedisService redisService;
    
    @Autowired
    private UserFavoriteQuestionMapper userFavoriteQuestionMapper;

    /**
     * 检查是否已收藏
     *
     * @param userId 用户ID
     * @param questionId 题目ID
     * @return 是否已收藏
     */
    public boolean isFavorite(Long userId, Long questionId) {
        String cacheKey = getCacheKey(userId);
        Long index = redisService.indexOfForList(cacheKey, questionId);
        return index != null && index >= 0;
    }

    /**
     * 添加收藏到缓存
     *
     * @param userId 用户ID
     * @param questionId 题目ID
     */
    public void addFavorite(Long userId, Long questionId) {
        String cacheKey = getCacheKey(userId);
        redisService.leftPushForList(cacheKey, questionId);
        redisService.expire(cacheKey, CacheConstants.FAVORITE_EXPIRE_TIME, TimeUnit.DAYS);
    }

    /**
     * 从缓存中移除收藏
     *
     * @param userId 用户ID
     * @param questionId 题目ID
     */
    public void removeFavorite(Long userId, Long questionId) {
        String cacheKey = getCacheKey(userId);
        redisService.removeForList(cacheKey, questionId);
        redisService.expire(cacheKey, CacheConstants.FAVORITE_EXPIRE_TIME, TimeUnit.DAYS);
    }


    /**
     * 检查Redis key是否存在
     *
     * @param userId 用户ID
     * @return 是否存在缓存
     */
    public boolean hasCache(Long userId) {
        String cacheKey = getCacheKey(userId);
        return redisService.hasKey(cacheKey);
    }

    /**
     * 刷新缓存（从数据库加载到Redis）
     *
     * @param userId 用户ID
     */
    public void refreshCache(Long userId) {
        String cacheKey = getCacheKey(userId);
        
        // 从数据库查询用户收藏的题目ID列表
        List<UserFavoriteQuestion> favorites = userFavoriteQuestionMapper.selectList(
            new LambdaQueryWrapper<UserFavoriteQuestion>()
                .eq(UserFavoriteQuestion::getUserId, userId)
                .orderByDesc(UserFavoriteQuestion::getCreateTime)
        );
        
        // 删除旧的缓存
        redisService.deleteObject(cacheKey);
        
        // 提取题目ID列表
        List<Long> questionIds = favorites.stream()
            .map(UserFavoriteQuestion::getQuestionId)
            .toList();
        
        // 批量插入到Redis（即使为空也会创建key）
        if (!questionIds.isEmpty()) {
            redisService.rightPushAll(cacheKey, questionIds);
        } else {
            // 即使没有收藏，也要创建空的Redis key
            redisService.rightPushAll(cacheKey, List.of("-1"));
        }
        
        // 设置过期时间
        redisService.expire(cacheKey, CacheConstants.FAVORITE_EXPIRE_TIME, TimeUnit.DAYS);
    }

    /**
     * 获取缓存键
     *
     * @param userId 用户ID
     * @return 缓存键
     */
    private String getCacheKey(Long userId) {
        return CacheConstants.USER_FAVORITE_QUESTION_KEY + userId;
    }
}
